const app = getApp();
var config = require('../../utils/parts');
var md5 = require('../../utils/md5');
var globalOption = null;
Page({
    data: {
      baseImgUrl: config.imgUrl,//图片地址
        baseRequestUrl:config.apiUrl//线上接口地址
    },
    onReady:function(){
        var _this = this;
        //创建动画
        var animationLight = wx.createAnimation({
            duration:100,
            timingFunction:'linear',
            delay:0
        })

        setInterval(function(){
            animationLight.rotate(90).step()
                          .rotate(90).step()
                          .rotate(90).step()
                          .rotate(90).step()
                          .rotate(90).step()
                          .rotate(90).step()
                          .rotate(90).step()
                          .rotate(90).step()
            _this.setData({
                animationLight:animationLight.export()
            })
        }.bind(_this),2000);
    },
    onLoad: function (option){
      globalOption = option;
    },
    onShow: function () {
          var option=globalOption;
          var _this = this,
          accept_salt = app.globalData.session_key.salt, 
          accept_userId = app.globalData.session_key.userId,
            launch_option, accept_option;
            console.log(option);
            var nickName = wx.getStorageSync("nickName");
            var avatarUrl = wx.getStorageSync("avatarUrl");
            if (nickName == "") {
              wx.navigateTo({
                url: "/pages/authorize/authorize"
              });
              return false;
            }
            app.globalData.nickName = wx.getStorageSync("nickName");
            app.globalData.avatarUrl = wx.getStorageSync("avatarUrl");
            wx.showLoading({
              title: '',
              mask: true
            });
            if (accept_salt && accept_userId){
              wx.checkSession({
                success:function(){
                  _this.setData({
                    accept_nickName: app.globalData.nickName,
                    accept_headImgUrl: app.globalData.avatarUrl
                  });
                  wx.request({
                    url: _this.data.baseRequestUrl + 'pk',
                    method: 'POST',
                    header: {
                      'content-type': 'application/x-www-form-urlencoded'
                    },
                    data: {
                      userId: accept_userId,
                      salt: accept_salt,
                      shareId: option.shareId,
                      shareToken: option.shareToken
                    },
                    success: function (res) {
                      if (res.statusCode != 200) {
                        getApp().showModal("服务器异常");
                        return
                      }
                      switch (res.data.code) {
                        case 200:
                          launch_option = res.data.data.share,
                            accept_option = res.data.data.me;
                          _this.setData({
                            launch_headImgUrl: launch_option.headimgurl,
                            launch_nickName: launch_option.nickname,
                            launch_type: launch_option.type,
                            launch_score: launch_option.score,
                            accept_type: accept_option.type,
                            accept_score: accept_option.score,
                            launch_car: {
                              a: launch_option.a,
                              b: launch_option.b,
                              c: launch_option.c,
                              d: launch_option.d,
                              e: launch_option.e,
                              f: launch_option.f,
                              g: launch_option.g,
                              h: launch_option.h
                            },
                            accept_car: {
                              a: accept_option.a,
                              b: accept_option.b,
                              c: accept_option.c,
                              d: accept_option.d,
                              e: accept_option.e,
                              f: accept_option.f,
                              g: accept_option.g,
                              h: accept_option.h
                            }
                          })
                          _this.doScoreAnalysis(launch_option.score, 'launch');
                          _this.doScoreAnalysis(accept_option.score, 'accept');
                          _this.doImgUrl(_this.data.accept_car, 'accept');
                          _this.doImgUrl(_this.data.launch_car, 'launch');
                          _this.doPartsImgUrl(_this.data.launchImgUrl, 'launch');
                          _this.doPartsImgUrl(_this.data.acceptImgUrl, 'accept');
                          _this.doPartsName(_this.data.launch_car, 'launch');
                          _this.doPartsName(_this.data.accept_car, 'accept');
                          _this.doStarWidth(res.data.data.share, 'launch');
                          _this.doStarWidth(res.data.data.me, 'accept');
                          _this.doPartsScore(res.data.data.share, 'launch');
                          _this.doPartsScore(res.data.data.me, 'accept');
                          _this.doPkResult();
                          break;
                        case 401:
                          _this.showMsg('参数为空', 'none');
                          break;
                        case 402:
                          _this.showMsg('shareToken验证错误', 'none');
                          break;
                        case 403:
                          _this.showMsg('userId和shareId相同', 'none');
                          break;
                        case 301:
                          _this.showMsg('userId错误', 'none');
                          break;
                        case 302:
                          _this.showMsg('salt错误', 'none');
                          break;
                        case 303:
                          _this.showMsg('你还没买车', 'none');
                          wx.navigateTo({
                            url: '../index/index'
                          })
                          break;
                        case 304:
                          _this.showMsg('shareId错误', 'none');
                          break;
                        case 305:
                          _this.showMsg('分享者没有车', 'none');
                          break;
                        case 800:
                          getApp().showModal(res.data.data.msg);
                          wx.hideLoading();
                        default:
                          _this.showMsg('pk接口返回错误', 'none');
                          break;
                      }
                      wx.hideLoading();
                    },
                    fail: function (res) {
                      console.log("checksession成功后PK接口fail");
                      console.log(res);
                      getApp().showModal("网络奔溃啦，请关闭后重试哦！");
                    }
                  })
                },
                fail:function(res){
                  wx.navigateTo({
                    url: "/pages/authorize/authorize"
                  });
                }
              });
            }else{
              wx.navigateTo({
                url: "/pages/authorize/authorize"
              });
            }
        
    },
    doPkResult(){
        var _this = this,
            pk_result = [],
            o = _this.data;
        pk_result.push(_this.battle(Number(o.launch_score),Number(o.accept_score)));
        for(var i = 0; i < o.launch_parts_score.length; i++){
            pk_result.push(_this.battle(Number(o.launch_parts_score[i]),Number(o.accept_parts_score[i])))
        }
        _this.setData({
            pk_result:pk_result
        })
    },
    battle(num1,num2){
        var res;
            if(num1  == num2){
                res = 0
            }else{
                (num1 > num2) ? res = 'left' : res = 'right'
            }
        return res
    },
    doPartsScore(obj, goal) {
        var _this = this;
        var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'],
            parts_score = [];

        for (var i = 0; i < arr.length; i++) {
            if (obj[arr[i]] != '') {
                var colorAddition;
                if (obj[arr[i]][0] == 'a' || obj[arr[i]][0] == 'h') {
                    colorAddition = 0;
                } else {
                    colorAddition = config.getColorAddition(obj[arr[i]][2]);
                }
                var baseAttribute = config.getBaseAttribute(obj[arr[i]][0], obj[arr[i]][1]);

                parts_score.push(config.getPartsScore(obj[arr[i]][1], colorAddition, baseAttribute));
            } else {
                parts_score.push('');
            }
        }
        if (goal == 'launch') {
            _this.setData({
                launch_parts_score: parts_score
            })
        }else if(goal == 'accept'){
            _this.setData({
                accept_parts_score: parts_score
            })
        }
    },
    doStarWidth(obj, goal) {
        var _this = this;

        var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'],
            star_width = [];
        for (var i = 0; i < arr.length; i++) {
            if (obj[arr[i]] != '') {
                star_width.push(obj[arr[i]][1] * 20 + 'rpx');
            } else {
                star_width.push('0rpx');
            }
        }

        if (goal == 'launch') {
            var launch_star = [];
            for (var i in star_width) {
                launch_star.push(star_width[i])
            }
            _this.setData({
                launch_star: launch_star
            })
        }else if(goal == 'accept'){
            var accept_star = [];
            for(var i in star_width){
                accept_star.push(star_width[i])
            }
            _this.setData({
                accept_star:accept_star
            })
        }
    },
    showMsg(txt, icon) {
        wx.showToast({
            title: txt,
            icon: icon
        })
    },
    doPartsName(obj,goal) {
        var _this = this,
            car = obj,
            parts = {};
        for (var key in car) {
            if (key == 'h' && car[key] != '') {
                parts[key] = config[key][car[key][1]][car[key][2]].name
            } else if (key == 'a' && car[key] != '') {
                parts[key] = config[key][car[key][1]].name
            } else {
                if (car[key] != '') {
                    parts[key] = config[key][car[key][1]].name + '（' + config.color[car[key][2] - 1] + '）'
                } else {
                    parts[key] = ''
                }
            }
        }
        if(goal == 'launch'){
            _this.setData({
                launchPartsName: parts
            })
        }else if(goal == 'accept'){
            _this.setData({
                acceptPartsName: parts
            })
        }

    },
    doPartsImgUrl(obj,goal) {
        var _this = this,
            parts = {};
        for (var key in obj) {
            if (obj[key] == '') {
                parts[key] = _this.data.baseImgUrl + '/pk-parts-item-off.png';
            } else {
                parts[key] = obj[key].replace(/big/, 'small');
            }
        }
        //拼图中没有h高级配件，需单独操作
        if (_this.data.launch_car.h == '') {
            parts.launch_imgUrl_h = _this.data.baseImgUrl + '/pk-parts-item-off.png';
        } else {
            parts.launch_imgUrl_h = _this.data.baseImgUrl + '/parts/h/' + _this.data.launch_car.h + '_small.png';
        }
        if (_this.data.accept_car.h == '') {
            parts.accept_imgUrl_h = _this.data.baseImgUrl + '/pk-parts-item-off.png';
        } else {
            parts.accept_imgUrl_h = _this.data.baseImgUrl + '/parts/h/' + _this.data.accept_car.h + '_small.png';
        }
        if(goal == 'launch'){
            _this.setData({
                launchPartsImg: parts
            })
        }else if(goal = 'accept'){
            _this.setData({
                acceptPartsImg: parts
            })
        }
    },
    doImgUrl: function (obj, goal) {
        //拼图部分图片
        var _this = this;
        let baseArr = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
        let arr = obj;
        let resArr = [];

        for (var i = 0; i < baseArr.length; i++) {
            if (arr[baseArr[i]] != '') {
                resArr.push(_this.data.baseImgUrl + '/parts/' + arr[baseArr[i]][0] + '/' + arr[baseArr[i]] + '_big.png');
            } else {
                resArr.push('');
            }
        }
        if (goal == 'launch') {
            var launchImgUrl = {};
            launchImgUrl.launch_imgUrl_a = resArr[0];
            launchImgUrl.launch_imgUrl_b = resArr[1];
            launchImgUrl.launch_imgUrl_c = resArr[2];
            launchImgUrl.launch_imgUrl_d = resArr[3];
            launchImgUrl.launch_imgUrl_e = resArr[4];
            launchImgUrl.launch_imgUrl_f = resArr[5];
            launchImgUrl.launch_imgUrl_g = resArr[6];
            _this.setData({
                launchImgUrl: launchImgUrl
            })
        } else if (goal == 'accept') {
            var acceptImgUrl = {};
            acceptImgUrl.accept_imgUrl_a = resArr[0];
            acceptImgUrl.accept_imgUrl_b = resArr[1];
            acceptImgUrl.accept_imgUrl_c = resArr[2];
            acceptImgUrl.accept_imgUrl_d = resArr[3];
            acceptImgUrl.accept_imgUrl_e = resArr[4];
            acceptImgUrl.accept_imgUrl_f = resArr[5];
            acceptImgUrl.accept_imgUrl_g = resArr[6];
            _this.setData({
                acceptImgUrl: acceptImgUrl
            })
        }
    },
    doScoreAnalysis: function (num, goal) {
        if (num == '') return;
        //分析分数,获取车名
        var index = parseInt(num / 15000);
        if (index > 34) index = 34;
        var nameArr = ['SUV概念车', '越野一族', '商务座驾'];
        var arr = ['青铜级,lv1,level-qt.png', '青铜级,lv2,level-qt.png', '青铜级,lv3,level-qt.png', '青铜级,lv4,level-qt.png', '青铜级,lv5,level-qt.png',
            '白银级,lv1,level-by.png', '白银级,lv2,level-by.png', '白银级,lv3,level-by.png', '白银级,lv4,level-by.png', '白银级,lv5,level-by.png',
            '黄金级,lv1,level-hj.png', '黄金级,lv2,level-hj.png', '黄金级,lv3,level-hj.png', '黄金级,lv4,level-hj.png', '黄金级,lv5,level-hj.png',
            '铂金级,lv1,level-bj.png', '铂金级,lv2,level-bj.png', '铂金级,lv3,level-bj.png', '铂金级,lv4,level-bj.png', '铂金级,lv5,level-bj.png',
            '钻石级,lv1,level-zs.png', '钻石级,lv2,level-zs.png', '钻石级,lv3,level-zs.png', '钻石级,lv4,level-zs.png', '钻石级,lv5,level-zs.png',
            '大师级,lv1,level-ds.png', '大师级,lv2,level-ds.png', '大师级,lv3,level-ds.png', '大师级,lv4,level-ds.png', '大师级,lv5,level-ds.png',
            '王者级,lv1,level-wz.png', '王者级,lv2,level-wz.png', '王者级,lv3,level-wz.png', '王者级,lv4,level-wz.png', '王者级,lv5,level-wz.png'];

        var res = arr[index].split(',');

        if (goal == 'launch') {
            this.setData({
                launch_carRank: res[0],
                launch_carLevel: res[1],
                launch_carIconUrl: this.data.baseImgUrl + '/' + res[2],
                launch_carName: nameArr[this.data.launch_type - 1]
            })
        } else if (goal = 'accept') {
            this.setData({
                accept_carRank: res[0],
                accept_carLevel: res[1],
                accept_carIconUrl: this.data.baseImgUrl + '/' + res[2],
                accept_carName: nameArr[this.data.accept_type - 1]
            })
        }
    },
    back: function () {
        wx.redirectTo({
            url: '../index/index'
        })
    }, 
    onShareAppMessage: function (res) {
      return {
        title: getApp().shareTitle2(),
        path: "/pages/index/index"
      }
    },
})